/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.myapp.metier;

import java.util.Date;
import java.util.Iterator;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Query;

/**
 *
 * @author HP
 */
public class Helper {

    Session session = null;

    public Helper() {
        this.session = HibernateUtil.getSessionFactory().getCurrentSession();
    }

    public void addOrder() {

        Order order = new Order(1, 123, 144, new Date(), 1000, "Gros client");
        try {

            org.hibernate.Transaction tx = session.beginTransaction();
            session.save(order);
            tx.commit();
        } catch (HibernateException ex) {
            System.out.println(ex);
        }

    }

    public void addOrder(int typeOperation, int compteClient, int quantity, int price, String typeClient) {

        Order order = new Order(typeOperation, compteClient, quantity, new Date(), price, typeClient);
        try {

            org.hibernate.Transaction tx = session.beginTransaction();
            session.save(order);
            tx.commit();
        } catch (HibernateException ex) {
            System.out.println(ex);
        }

    }

    public void addOrderDiffere(int typeOperation, int compteClient, int quantity, int price) {

        OrderDiffere orderdiffere = new OrderDiffere(typeOperation, compteClient, quantity, new Date(), price, "Agence Regionale");
        try {

            org.hibernate.Transaction tx = session.beginTransaction();
            session.save(orderdiffere);
            tx.commit();
        } catch (HibernateException ex) {
            System.out.println(ex);
        }

    }

    public int countOrderDifferes() {
        int count = 0;
        try {
            org.hibernate.Transaction tx = session.beginTransaction();

            Query q = session.createQuery("SELECT COUNT(*) FROM OrderDiffere");
            if (!q.list().isEmpty()) {
                count = Integer.valueOf((String) q.uniqueResult().toString());
            }
            tx.commit();
        } catch (HibernateException ex) {
            System.out.println(ex);
        }
        return count;
    }

    public void deleteOrderDifferes() {
        try {
            org.hibernate.Transaction tx = session.beginTransaction();
            List ordreList = session.createQuery("FROM OrderDiffere").list();
            for (Iterator it = ordreList.iterator(); it.hasNext();) {
                OrderDiffere  order = (OrderDiffere) it.next();
                session.delete(order);
            }

            tx.commit();
        } catch (HibernateException ex) {
            System.out.println(ex);
        }
    }

}
